import request from '@/axios/request';

interface ApiResponse<T> {
  code: number;
  data: T;
  message?: string;
}

interface MaterialOption {
  code: string;
  type: string;
  description: string;
  currentStock: number;
}

interface RawMaterialData {
  code?: string;
  Code?: string;
  type?: string;
  Type?: string;
  description?: string;
  Description?: string;
  currentstock?: number;
  CurrentStock?: number;
  current_stock?: number;
}

// 获取入库记录列表
export function getStorageInList(params: {
  search?: string
  start_date?: string
  end_date?: string
}) {
  return request({
    url: '/package-material/storage-in/list',
    method: 'get',
    params
  })
}

// 新增入库记录
export function addStorageIn(data: {
  storageNumber: string
  materialCode: string
  quantity: number
  remark?: string
  operator?: string
}) {
  return request({
    url: '/package-material/storage-in/add',
    method: 'post',
    data
  }).catch(error => {
    console.error('Storage in error:', error.response?.data || error);
    throw error;
  })
}

// 获取可入库的包材列表
export function getMaterialOptions(): Promise<ApiResponse<MaterialOption[]>> {
  return request({
    url: '/package-material/storage-in/materials',
    method: 'get'
  }).then(res => {
    const response = res.data as ApiResponse<RawMaterialData[]>;
    if (response.code === 200 && Array.isArray(response.data)) {
      // 确保数据格式正确
      const formattedData: MaterialOption[] = response.data.map(item => {
        // 尝试获取库存值
        let stock = 0;
        if ('currentstock' in item && item.currentstock !== undefined) stock = item.currentstock;
        else if ('CurrentStock' in item && item.CurrentStock !== undefined) stock = item.CurrentStock;
        else if ('current_stock' in item && item.current_stock !== undefined) stock = item.current_stock;
        
        return {
          code: item.code || item.Code || '',
          type: item.type || item.Type || '',
          description: item.description || item.Description || '',
          currentStock: Number(stock)
        };
      });
      response.data = formattedData;
    }
    return response as ApiResponse<MaterialOption[]>;
  });
} 